const app = getApp();


const requestParamHandler = (params) =>{
  // console.log(Object.keys(params));
  // console.log(typeof params);
  if(typeof params=='object'){
      for(let key in params){
        // console.log("key:"+key);
        // console.log("vue:"+params[key]);

        if(params[key]==null || params[key]==undefined){
            delete(params[key]);
        }
        if(params[key] instanceof Array){
          const arr=[];
          const list=params[key];
          for(let listElement of list){
            const abj=requestParamHandler(listElement);
            abj && arr.push(abj)
          }
          params[key]=arr;

        }
      }
  }

  return params;
};

const request = (method,url, data,response,error) => {
        // wx.showLoading({
        //   title: '加载中...',
        //   mask: true 
        // })
       wx.request({
           url: app.globalData.base_url+url,
           method: method,
           data: requestParamHandler(data) || {},
           header: {
               'token':wx.getStorageSync(app.globalData.TOKEN),  
           },
           success:res => {
            // console.log(JSON.stringify(res.data))
              return response(res)           
           },
           fail: err => {
            return error(err)
           },
           complete: info => {
            // wx.hideLoading();
          }
       })
}

module.exports = {
  // requestGet:(url, data, response, error)=>get('GET', url, data, response, error),
  // requestPost:(url, data, response, error)=>post('POST', url, data, response, error),
  // requestPut:(url, data, response, error)=>put('PUT', url, data, response, error),
  // requestRemove:(url, data, response, error)=>remove('DELETE', url, data, response, error),
  get: (url, data, response, error) => request('GET', url, data, response, error),
  post: (url, data, response, error) => request('POST', url, data, response, error),
  put: (url, data, response, error) => request('PUT', url, data, response, error),
  delete: (url, data, response, error) => request('DELETE', url, data, response, error),
}